package models;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

import org.apache.commons.lang.StringUtils;

import play.db.jpa.GenericModel;
import play.db.jpa.JPABase;
import play.libs.Codec;

@MappedSuperclass
public class BasicModel extends GenericModel{
	
	@Id
	public String id;
	
	@Column(name = "update_time")
	public Long updateTime;
	
	@Column(name = "create_time")
	public Long createTime;
	
	//0代表存在,1代表删除
	@Column(name = "is_delete",columnDefinition = "int default 0")
	public int isDelete;
	
	void beforeSave(){
		long now = System.currentTimeMillis();
		if (createTime == null) {
			createTime = now;
		}
		if (StringUtils.isEmpty(id)) {
			id =  Codec.UUID().replace("-", "").toUpperCase();
		}
		updateTime = now;
	}
	
	@Override
	public <T extends JPABase> T save() {
		beforeSave();
		return super.save();
	}
	
	@Override
	public void _save() {
		beforeSave();
		super._save();
	}

	public String getId() {
		return id;
	}

	@Override
	public Object _key() {
		return getId();
	}
	
	/**
     * 逻辑删除
     * @param <T>
     * @return
     */
    public <T extends JPABase> T remove() {
        isDelete = 1;
        return save();
    }
    
    /**
     * @deprecated 逻辑删除，请使用remove();
     * @param <T>
     * @return
     */
    @Override
    public <T extends JPABase> T delete() {
        return super.delete();
    }

}
